package com.ljqc.sbom.management.util;


import org.apache.maven.artifact.versioning.ComparableVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.zafarkhaja.semver.Version;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


public class VersionMatcher {
    public static Logger logger = LoggerFactory.getLogger(VersionMatcher.class);

    private static final String GREATER_THAN = ">";
    private static final String EQUAL = "=";
    private static final String LESS_THAN = "<";
    private static final String WAVE_SYMBOL = "~";
    private static final String HAT_SYMBOL = "^";
    private static final String WAVE_REGEX = "^~(\\d\\.)+";
    private static final String HAT_REGEX = "^\\^(\\d\\.)+";
    private static final Integer COMPARE_GREATER = 1;
    private static final Integer COMPARE_LESS = -1;
    private static final String COMMON_VERSION_REGEX = "^\\w{0,5}\\.\\w{0,5}(\\.\\w{0,5})*([-\\.][\\da-zA-Z\\.]+)*$";
    private static final String COMMON_SINGLE_VERSION_REGEX = "^[v0-9]{1,4}([-\\.][\\da-zA-Z\\.]+)*$";


    /**
     * common version like a.b.c-patch
     * common eg: 1.9.1
     * uncommon eg: 20030211.134440
     */
    public static boolean isCommonVersion(String version) {
        if (MatchUtil.isMatch(version, COMMON_VERSION_REGEX) || MatchUtil.isMatch(version, COMMON_SINGLE_VERSION_REGEX)) {
            return true;
        }
        return false;
    }

    public static String getMavenCleanVersion(List<String> cleanVersionList, String currentVersion) {
        if (CollectionUtils.isEmpty(cleanVersionList)) {
            return null;
        }
        sortMavenVersion(cleanVersionList);
        List<String> collect = cleanVersionList.stream().filter(e ->
        {
            ComparableVersion v1 = new ComparableVersion(e);
            ComparableVersion v2 = new ComparableVersion(currentVersion);
            return v1.compareTo(v2) > 0;
        }).collect(Collectors.toList());
        if (collect.isEmpty()) {
            return null;
        }
        return collect.get(0);
    }

    public static void sortMavenVersion(List<String> versions) {
        if (!CollectionUtils.isEmpty(versions)) {
            versions.sort((o1, o2) ->
            {
                ComparableVersion v1 = new ComparableVersion(String.valueOf(o1));
                ComparableVersion v2 = new ComparableVersion(String.valueOf(o2));
                return v1.compareTo(v2);
            });
        }
    }

    public static void main(String[] args) {
        Version v = Version.valueOf("5.7.1");
        String statement = "2 >=2.2.1 | 3.x | 4 | 5";
        String[] s = statement.split(">");
        String s1 = s[0];
        s[0] = s1 + "| >";
        String join = String.join("", s);
        System.out.println(join);


        boolean satisfies = v.satisfies(join);
        System.out.println(satisfies);
    }
}
